<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$articleTable = 'article';
$categoryTable = 'categories';

$article = [];
$categories = [];
$error = '';
$success = '';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 加载文章数据
if ($id <= 0) {
    header('Location: article.php?error=文章ID无效');
    exit;
}

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // 加载分类
    $stmt = $pdo->query("SELECT id, name FROM $categoryTable ORDER BY sort_order ASC");
    $categories = $stmt instanceof PDOStatement ? $stmt->fetchAll() : [];

    // 加载文章
    $stmt = $pdo->prepare("SELECT * FROM $articleTable WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $article = $stmt->fetch();
    if (!$article) {
        header('Location: article.php?error=文章不存在');
        exit;
    }
} catch (PDOException $e) {
    $error = "数据加载失败：" . $e->getMessage();
}

// 处理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $categoryId = (int)($_POST['category_id'] ?? 0);
    $status = (int)($_POST['status'] ?? 0);
    $articleType = $_POST['article_type'] ?? 'doc';
    $content = '';

    // 处理内容
    if ($articleType === 'steps') {
        $steps = $_POST['steps'] ?? [];
        if (empty($steps)) {
            $error = "请至少添加一个操作步骤";
        } else {
            foreach ($steps as $index => $step) {
                $stepContent = trim($step['content'] ?? '');
                if (!empty($stepContent)) {
                    $content .= ($index + 1) . ". " . $stepContent . "\n\n";
                }
            }
            if (empty($content)) $error = "步骤内容不能为空";
        }
    } else {
        $content = trim($_POST['content'] ?? '');
        if (empty($content)) $error = "文章内容不能为空";
    }

    // 基础验证
    if (empty($title)) $error = "文章标题不能为空";
    elseif ($categoryId <= 0) $error = "请选择分类";
    elseif (!$error) {
        try {
            $stmt = $pdo->prepare("UPDATE $articleTable SET 
                title = :title, 
                content = :content, 
                category_id = :category_id, 
                status = :status, 
                article_type = :article_type, 
                update_time = NOW() 
                WHERE id = :id");
            $stmt->execute([
                ':title' => $title,
                ':content' => $content,
                ':category_id' => $categoryId,
                ':status' => $status,
                ':article_type' => $articleType,
                ':id' => $id
            ]);
            header('Location: article.php?success=文章更新成功');
            exit;
        } catch (PDOException $e) {
            $error = "更新失败：" . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章 - 知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏同添加页 -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item"><a href="index.php" class="nav-link"><i class="fas fa-home"></i><span>管理首页</span></a></li>
                <li class="nav-item"><a href="article.php" class="nav-link active"><i class="fas fa-file-alt"></i><span>文章管理</span></a></li>
                <li class="nav-item"><a href="category.php" class="nav-link"><i class="fas fa-folder"></i><span>分类管理</span></a></li>
                <li class="nav-item"><a href="version.php" class="nav-link"><i class="fas fa-sync-alt"></i><span>版本管理</span></a></li>
                <li class="nav-item"><a href="user.php" class="nav-link"><i class="fas fa-users"></i><span>用户管理</span></a></li>
                <li class="nav-item"><a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></a></li>
            </ul>
        </aside>

        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">编辑文章</h1>
                    <a href="article.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i>返回列表</a>
                </div>

                <?php if ($success): ?>
                    <div class="message message-success"><i class="fas fa-check-circle"></i><?php echo $success; ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error"><i class="fas fa-exclamation-circle"></i><?php echo $error; ?></div>
                <?php endif; ?>

                <?php if ($article): ?>
                <div class="form-card">
                    <form method="POST" action="" id="articleForm">
                        <div class="form-group">
                            <label class="form-label" for="title">文章标题 <span style="color: #EF4444;">*</span></label>
                            <input type="text" id="title" name="title" class="form-control" 
                                value="<?php echo htmlspecialchars($_POST['title'] ?? $article['title']); ?>" placeholder="请输入文章标题">
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label" for="category_id">所属分类 <span style="color: #EF4444;">*</span></label>
                                <select id="category_id" name="category_id" class="form-control">
                                    <option value="0">请选择分类</option>
                                    <?php foreach ($categories as $cate): ?>
                                        <option value="<?php echo $cate['id']; ?>" 
                                            <?php echo (isset($_POST['category_id']) ? $_POST['category_id'] : $article['category_id']) == $cate['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cate['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label" for="status">状态</label>
                                <select id="status" name="status" class="form-control">
                                    <option value="0" <?php echo (isset($_POST['status']) ? $_POST['status'] : $article['status']) == 0 ? 'selected' : ''; ?>>草稿</option>
                                    <option value="1" <?php echo (isset($_POST['status']) ? $_POST['status'] : $article['status']) == 1 ? 'selected' : ''; ?>>已发布</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">文章类型</label>
                            <div class="radio-group">
                                <label class="radio-item">
                                    <input type="radio" name="article_type" value="doc" 
                                        <?php echo (isset($_POST['article_type']) ? $_POST['article_type'] : $article['article_type']) == 'doc' ? 'checked' : ''; ?>>
                                    <span class="radio-custom"></span>
                                    <span>说明文档</span>
                                </label>
                                <label class="radio-item">
                                    <input type="radio" name="article_type" value="steps" 
                                        <?php echo (isset($_POST['article_type']) ? $_POST['article_type'] : $article['article_type']) == 'steps' ? 'checked' : ''; ?>>
                                    <span class="radio-custom"></span>
                                    <span>操作步骤</span>
                                </label>
                            </div>
                        </div>

                        <!-- 说明文档编辑器 -->
                        <div id="doc_content_group" class="form-group">
                            <label class="form-label" for="content">文章内容 <span style="color: #EF4444;">*</span></label>
                            <div class="markdown-editor">
                                <textarea id="content" name="content"><?php echo htmlspecialchars($_POST['content'] ?? $article['content']); ?></textarea>
                            </div>
                        </div>

                        <!-- 步骤文档表单 -->
                        <div id="steps_content_group" class="form-group" style="display: none;">
                            <label class="form-label">操作步骤 <span style="color: #EF4444;">*</span></label>
                            <div class="steps-container" id="steps_container"></div>
                            <button type="button" class="add-step-btn" id="add_step_btn">
                                <i class="fas fa-plus"></i> 添加步骤
                            </button>
                        </div>

                        <div class="form-actions">
                            <div>
                                <button type="button" class="btn btn-outline" id="import_btn">
                                    <i class="fas fa-upload"></i> 导入
                                    <div class="tooltip">
                                        <i class="fas fa-info-circle tooltip-icon"></i>
                                        <span class="tooltip-text">
                                            导入支持.md格式文件<br>
                                            导入后会覆盖当前内容<br>
                                            步骤文档建议按"1. 内容"格式编写
                                        </span>
                                    </div>
                                </button>
                                <button type="button" class="btn btn-outline" id="export_btn" style="margin-left: 0.5rem;">
                                    <i class="fas fa-download"></i> 导出
                                </button>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i>更新文章</button>
                                <a href="article.php" class="btn btn-outline" style="margin-left: 0.5rem;">取消</a>
                            </div>
                        </div>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- 上传弹窗和导入弹窗同添加页 -->
    <div class="modal-backdrop" id="upload_modal">
        <!-- 内容同添加页 -->
    </div>
    <div class="modal-backdrop" id="import_modal">
        <!-- 内容同添加页 -->
    </div>

    <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
    <script>
        // 逻辑同添加页，额外处理编辑页的步骤初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化编辑器（同添加页）
            
            // 初始化步骤（如果是步骤类型）
            const articleType = '<?php echo $article['article_type'] ?? 'doc'; ?>';
            if (articleType === 'steps') {
                const content = `<?php echo addslashes($article['content'] ?? ''); ?>`;
                const lines = content.split('\n');
                lines.forEach(line => {
                    line = line.trim();
                    if (line) {
                        const stepContent = line.replace(/^\d+\.\s*/, '');
                        addStep({ content: stepContent });
                    }
                });
            }

            // 其他逻辑同添加页
        });
    </script>
</body>
</html>